//
//  TouchFaceID.swift
//  SwiftProject
//
//  Created by qindong on 2021/3/4.
//

import UIKit
import LocalAuthentication

enum IDType {
    case touch
    case face
    case none
}

class TouchFaceID: NSObject {
    static var manager = TouchFaceID()
    private override init() {
        super.init()
    }
    
    let context = LAContext()
    var idType : IDType = .none
    
    //MARK:- 检查是否可以使用ID
    func isIdAvailable() -> Bool {
        let isIdAvailable = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
        return isIdAvailable
    }
    
    //MARK:- 判断支持哪种id
    func isFaceOrTouchID() -> IDType {
        if context.biometryType == .touchID {
            idType = .touch
        } else if context.biometryType == .faceID {
            idType = .face
        } else {
            idType = .none
        }
        return idType
    }
    
/**
     **LAError几种情况**
     LAErrorAuthenticationFailed  验证失败
     LAErrorUserCancel  用户取消验证
     LAErrorUserFallback  用户点击了右侧按钮
     LAErrorSystemCancel  系统取消  例如突然来电话、按了Home键、锁屏...
     LAErrorBiometryNotEnrolled  设备没有录入指纹
     LAErrorPasscodeNotSet  设备没有设置密码 无法启动TouchID
     LAErrorBiometryNotAvailable  设备的TouchID无效
     LAErrorBiometryLockout  多次验证失败 TouchID被锁
     LAErrorAppCancel 当前软件被挂起取消了授权 (如突然来了电话,应用进入前台)
     LAErrorInvalidContext 当前软件被挂起取消了授权 (授权过程中,LAContext对象被释)
     LAErrorBiometryNotAvailable   生物识别不可用
     LAErrorBiometryNotEnrolled 生物识别未登记
     LAErrorBiometryLockout 生物识别已锁定
     LAErrorNotInteractive 生物识别无交互
     LAErrorWatchNotAvailable
 */
    func useAuthenticationWithMessage(message : String, backTitle :String, resultBlock : @escaping(_ result : LAError?, _ success : Bool) -> Void) {
        context.localizedFallbackTitle = backTitle
        context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: message) { (success, error) in
            if success {
                resultBlock(nil, true)
            } else {
                resultBlock(error as? LAError, false)
            }
        }
    }
}
